package com.ncloud.crm.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsDiscnt;
import com.ncloud.crm.entity.BsDiscntFee;
import com.ncloud.crm.entity.order.OrderDiscnt;
import com.ncloud.crm.entity.order.OrderDiscntFee;
import com.ncloud.crm.mapper.BsDiscntMapper;
import com.ncloud.crm.mapper.OrderDiscntMapper;
import com.ncloud.crm.service.BsDiscntFeeService;
import com.ncloud.crm.service.OrderAttrService;
import com.ncloud.crm.service.OrderDiscntFeeService;
import com.ncloud.crm.service.OrderDiscntService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderDiscntServiceImpl implements OrderDiscntService {
	
	private static final Logger logger = LogManager.getLogger(OrderDiscntServiceImpl.class);
	
	@Autowired
	private OrderDiscntMapper orderDiscntMapper;
	@Autowired
	private BsDiscntMapper bsDiscntMapper;
	@Autowired
	private OrderAttrService orderAttrService;
	@Autowired
	private OrderDiscntFeeService orderDiscntFeeService;
	@Autowired
	private BsDiscntFeeService bsDiscntFeeService;
	@Reference
	private SequenceService sequenceService;
	
	public List<OrderDiscnt> getByOrderId(Long orderId){
		List<OrderDiscnt> orderDiscnts = orderDiscntMapper.getDiscntByOrderId(orderId);
		return orderDiscnts;
	}
	
	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		OrderDiscnt orderDiscnt = JSON.parseObject(json.toJSONString(),OrderDiscnt.class);
		try {
			validation(orderDiscnt);
			orderDiscntMapper.insertOrderDiscnt(orderDiscnt);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		JSONObject discntSort = new JSONObject();
		JSONArray discntArray = new JSONArray();
		//JSONArray discntAttrArray = new JSONArray();
		JSONArray discntFeeArray = new JSONArray();

		JSONArray acctSyncFeeArray = new JSONArray();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		Date currentDate = new Date();
		if(json.containsKey(OrderNodeDefineUtils.ORDER_DISCNT)){
			JSONArray discntList = json.getJSONArray(OrderNodeDefineUtils.ORDER_DISCNT);
			for(int i=0;i<discntList.size();i++){
				JSONObject diccntObj = discntList.getJSONObject(i);

				JSONObject feeInfo = new JSONObject();

				JSONObject acctFee = new JSONObject();
				/*获取套餐信息*/
				OrderDiscnt orderDiscnt = JSON.parseObject(diccntObj.toJSONString(),OrderDiscnt.class);
				String modifyTag = orderDiscnt.getModifyTag();
				if(StringUtils.isEmpty(modifyTag)){
					throw new UserException(ResultEnum.PARAM_ERROR);
				}
				/*生成产品实例编码*/
				if(orderDiscnt.getDiscntInstId() == null){
					Long id = sequenceService.getSequence("seq_discnt_inst_id");
					orderDiscnt.setDiscntInstId(id);
					feeInfo.put(TableIdDefineUtils.DISCNT_INST_ID,id);
					/*约定序列*/
					if(diccntObj.containsKey("index")){
						discntSort.put(diccntObj.getString("index"),id);
						orderDiscnt.setIsBase("1");
					}else{
						discntSort.put(diccntObj.getString("discntId"),id);
						orderDiscnt.setIsBase("0");
					}

					//result.put(TableIdDefineUtils.DISCNT_INST_ID,id);
				}else{
					if(diccntObj.containsKey("index")){
						discntSort.put(diccntObj.getString("index"),orderDiscnt.getDiscntInstId());
						orderDiscnt.setIsBase("1");
					}else{
						discntSort.put(diccntObj.getString("discntId"),orderDiscnt.getDiscntInstId());
						orderDiscnt.setIsBase("0");
					}
				}
				/*处理费用基础信息*/
				feeInfo.put("custId",result.getLong(TableIdDefineUtils.CUST_ID));
				feeInfo.put("discntId",orderDiscnt.getDiscntId());
				feeInfo.put("discntName",orderDiscnt.getDiscntName());
				feeInfo.put("feeType","1");
				feeInfo.put("payType","1");//后付费
				orderAttrService.getFeeAttrInfo(diccntObj,Constant.ATTR_TYPE_DISCNT,feeInfo);
				/*处理费用基础信息end*/
			/*处理orderId*/
				if(orderDiscnt.getOrderId() == null ){
					if(!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))){
						if(modifyTag.equals(Constant.ADD)){
							throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"资费信息动作modifyTag不存在！");
						}
						throw new UserException(ResultEnum.ORDER_INFO_ERROR);
					}else{
						orderDiscnt.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));
						feeInfo.put(TableIdDefineUtils.ORDER_ID,result.getLong(TableIdDefineUtils.ORDER_ID));
					}
				}
			/*处理prodInstId*/
				if(orderDiscnt.getProdInstId() == null){
					if(!result.containsKey(TableIdDefineUtils.PROD_INST_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.PROD_INST_ID))){
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"资费信息产品实例不存在！"+TableIdDefineUtils.PROD_INST_ID);
					}else{
						orderDiscnt.setProdInstId(result.getLong(TableIdDefineUtils.PROD_INST_ID));
						feeInfo.put(TableIdDefineUtils.PROD_INST_ID,result.getLong(TableIdDefineUtils.PROD_INST_ID));
					}
				}
			/*根据时长信息技术生效和失效日期 begin*/
				/*获取计费周期和单位*/
				int billingCycle = 0;
				String cycleUnit = "M";
				if(diccntObj.containsKey("cycleUnit") && diccntObj.containsKey("billingCycle")){
					cycleUnit = diccntObj.getString("cycleUnit");
					billingCycle = diccntObj.getIntValue("billingCycle");
					JSONObject param = new JSONObject();
					param.put("cycleUnit",diccntObj.getString("cycleUnit"));
					param.put("billingCycle",diccntObj.getString("billingCycle"));
					/*套餐属性信息处理，含有变更的处理*/
				    //orderAttrService.geneAttrInfos(param,orderDiscnt.getDiscntInstId(),"1",discntAttrArray);
					//记录属性信息


				}else{
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"套餐计费周期或计费单位不存在！{billingCycle,cycleUnit}");
				}
			/*根据时长信息技术生效和失效日期 end*/
				if(modifyTag.equals(Constant.ADD)){
					orderDiscnt.setBeginDate(currentDate);
					orderDiscnt.setEndDate(DateUtils.getEndTime(null,billingCycle,cycleUnit));
					orderDiscnt.setCreateTime(currentDate);
					orderDiscnt.setCreateUser(json.getLong("userId"));

					/*费用记录时间*/
					feeInfo.put("beginDate",DateUtils.formatDate(currentDate,"yyyy-MM-dd HH:mm:ss"));
					feeInfo.put("endDate",Constant.END_DATE);
					feeInfo.put("createTime",DateUtils.formatDate(currentDate,"yyyy-MM-dd HH:mm:ss"));
					feeInfo.put("createUser",json.getLong("userId"));
					feeInfo.put("modifyTag",Constant.ADD);
				}else if(modifyTag.equals(Constant.UPDATE)){
					if(orderDiscnt.getDiscntInstId() != null){
						BsDiscnt bsDiscnt = bsDiscntMapper.getBsDiscntByPk(orderDiscnt.getDiscntInstId());
						if(bsDiscnt != null ){
							OrderDiscnt orderDiscntOld = JSON.parseObject(JSON.toJSONString(bsDiscnt),OrderDiscnt.class);
							logger.debug("旧节点信息："+JSON.toJSONString(bsDiscnt));
							orderDiscntOld.setEndDate(currentDate);
							orderDiscntOld.setUpdateTime(currentDate);
							orderDiscntOld.setUpdateUser(json.getLong("userId"));
							orderDiscntOld.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));
							orderDiscntOld.setModifyTag(Constant.DEL);
							discntArray.add(JSON.parseObject(JSON.toJSONString(orderDiscntOld)));
						}
						/*处理费用信息*/
						BsDiscntFee bsDiscntFee = bsDiscntFeeService.getDiscntFeeByK(orderDiscnt.getDiscntInstId());
						if(bsDiscntFee != null){
							OrderDiscntFee orderDiscntFeeOld = JSON.parseObject(JSON.toJSONString(bsDiscntFee),OrderDiscntFee.class);
							logger.debug("旧套餐费用信息："+JSON.toJSONString(bsDiscntFee));
							orderDiscntFeeOld.setEndDate(currentDate);
							orderDiscntFeeOld.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));
							orderDiscntFeeOld.setModifyTag(Constant.DEL);
							discntFeeArray.add(JSON.parseObject(JSON.toJSONString(orderDiscntFeeOld)));
						}
					}else{
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"当前节点nodeId不存在！");
					}

					/*新信息*/
					orderDiscnt.setBeginDate(currentDate);
					orderDiscnt.setEndDate(DateUtils.getEndTime(null,billingCycle,cycleUnit));
					orderDiscnt.setUpdateTime(currentDate);
					orderDiscnt.setUpdateUser(json.getLong("userId"));
					orderDiscnt.setModifyTag(Constant.ADD);
					/*/*处理费用信息*/
					feeInfo.put("beginDate",DateUtils.formatDate(currentDate,"yyyy-MM-dd HH:mm:ss"));
					feeInfo.put("endDate",Constant.END_DATE);
					feeInfo.put("modifyTag",Constant.ADD);

				}else if(modifyTag.equals(Constant.DEL)){
					orderDiscnt.setEndDate(currentDate);
					/*/*处理费用信息*/
					feeInfo.put("endDate",DateUtils.formatDate(currentDate,"yyyy-MM-dd HH:mm:ss"));
					feeInfo.put("modifyTag",Constant.DEL);
				}else{
					feeInfo.put("modifyTag",Constant.NO_CHANGE);
				}
				//orderAttrService.getFeeAttrInfo(diccntObj,Constant.ATTR_TYPE_DISCNT,)
				discntArray.add(JSON.parseObject(JSON.toJSONString(orderDiscnt)));

				/*保存套餐费用信息*/
				discntFeeArray.add(feeInfo);
				/*生成acct数据*/
				//{"userId":"27","orderId":"1234567890","custId":"9876543210","discntInstId":"1234554321","fee":"1234","createUserId":"27"}
				/*订单*/
				acctFee.put("orderId",orderDiscnt.getOrderId());
				/*客户id*/
				acctFee.put("custId",result.getLong(TableIdDefineUtils.CUST_ID));
				/*userId*/
				acctFee.put("userId",json.getLong("userId"));
				/*套餐实例iD*/
				acctFee.put("discntInstId",orderDiscnt.getDiscntInstId());
				/*渠道结算费用*/
				acctFee.put("fee",feeInfo.getLong("balance"));
				/*创建用户*/
				acctFee.put("createUserId",json.getLong("userId"));

				//
				acctSyncFeeArray.add(acctFee);
			}
			//组装套餐信息
			jsonObject.put(OrderNodeDefineUtils.ORDER_DISCNT,discntArray);
			//组装套餐费用信息
			jsonObject.put(OrderNodeDefineUtils.ORDER_DISCNT_FEE,discntFeeArray);
			//组装套餐属性节点信息
			//jsonObject.put(OrderNodeDefineUtils.ORDER_ITEM,discntAttrArray);
			/*存放acct费用数据*/
			jsonObject.put(OrderNodeDefineUtils.ACCT_SYNC_FEE,acctSyncFeeArray);
			/*保存套餐和节点对应关系处理*/
			result.put(OrderNodeDefineUtils.DISCNT_NODE_RELATION,discntSort);

		}
		return jsonObject;
	}

	private void validation(OrderDiscnt orderDiscnt){
		if(orderDiscnt.getDiscntInstId() == null){
			Long id = sequenceService.getSequence("seq_discnt_inst_id");
			orderDiscnt.setDiscntInstId(id);
		}
	}

	@Override
	public int updateByInstId(OrderDiscnt orderDiscnt) {
		
		return orderDiscntMapper.updateByInstId(orderDiscnt);
	}
}
